package com.stylefeng.guns.core.util.appSecure;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Signature;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//ser
public class AppSecureUtil {
	
	private static final Log log = LogFactory.getLog(AppSecureUtil.class);

	/**
	 * 解密接收到的数据
	 * @param request
	 * @return
	 * @throws IOException 
	 */
/*	public static String getDecryptResult(AppSecure obj) throws IOException {
		if(!checkDataMD5(obj)){
			log.error("M验证失败");
			return "";
		}
		
		if(!checkSignetMD5(obj)){
			log.error("S验证失败");
			return "";
		}
		
		return getDataByAesDecrypt(obj);
		//==
	}*/
	
	/**
	 * 返回结果数据,并对对结果数据签名
	 * @param obj
	 * @param content
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public static Map<String, Object> getSignature(AppSecure obj,String content) throws UnsupportedEncodingException{
		Map<String, Object> mapBack = new HashMap<String, Object>();
		
		byte[] password = getAesPassword(obj);
		byte[] encryptResult = getDataByAesEncrypt(content,password);
		//String signatureStr = getSignet(encryptResult);
		byte[] signatureStrBase64 = SharedBase64.encode(RSAUtil.sign(encryptResult));
		
		mapBack.put("encryptResult",new String(encryptResult, "utf-8"));
		mapBack.put("signatureStr",new String(signatureStrBase64, "utf-8"));
		return mapBack;
	}
	
	
	/** 校验data(jsonString)的Md5  */
	public static boolean checkDataMD5(AppSecure obj) {
		return StringUtils.equalsIgnoreCase(obj.getDataMD5(), obj.getM());
 
	}
	
	/** 校验 签名的Md5  */
	public static boolean checkSignetMD5(AppSecure obj) {
		return StringUtils.equalsIgnoreCase(obj.getParameterStr(), obj.getS());
	}
	
	/** 获取AES密码 */
	private static byte[] getAesPassword(AppSecure obj) {
		return RSAUtil.decrypt(SharedBase64.decode(obj.getK().getBytes())); //私钥解密 ,双方共用,返回客户端
	}
	
	/**
	 * AES解密数据
	 * @param obj 
	 * @return
	 */
	public static String getDataByAesDecrypt(AppSecure obj) throws IOException {
		byte[] password = getAesPassword(obj);
		return new String(AESUtil.decrypt(SharedBase64.decode(obj.getData()),new String(password)));
	}
	
	/**
	 * 服务端用AES密码对数据加密
	 * @param content 数据
	 * @param password AES密码
	 * @return
	 */
	public static byte[] getDataByAesEncrypt(String content,byte[] password) {
		byte[] encryptResult = AESUtil.encrypt(content.getBytes(), new String(password));
		byte[] result = SharedBase64.encode(encryptResult);
		return result;
		//return new String(result);
	}
 
	
	/**
	 * 生成签名
	 * @param result AES密码加密数据
	 * @return
	 */
	private static String getSignet(byte[] result){
		Signature signet = null;
		byte[] signed = null;
		try {
			signet = Signature.getInstance(RSAUtil.SIGN_ALGORITHMS); 
			signet.initSign(RSAUtil.getRSAPrivateKey(RSAUtil.privateEncode.getBytes()));
			signet.update(result);
			signed = signet.sign(); //对信息的数字签名
			return new String(signed);
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	
	
	//===main 加解密测试
	public static void main(String[] args) {
		/*
			jsonString={ 'key'：'00000000000000000000000'， 'imei'：'00000000000000000000000'， 'imsi'：'00000000000000000000000'， 'uuid'：2， 'versionCame'：'1.0.1'， 'versionCode'：2， 'platform'：'android'， 'model':'6s'， 'channel':'pingtai', 'brand':'sdk', 'product':'06', 'versionOS':'7.0', 'manufacturer':'huawei', 'appId':'com.afda', 'MessageBody'： [ {place:'index'} ] }
		 */
		String jsondata = "jsonString={ 'key'：'00000000000000000000000'， 'imei'：'00000000000000000000000'， 'imsi'：'00000000000000000000000'， 'uuid'：2， 'versionCame'：'1.0.1'， 'versionCode'：2， 'platform'：'android'， 'model':'6s'， 'channel':'pingtai', 'brand':'sdk', 'product':'06', 'versionOS':'7.0', 'manufacturer':'huawei', 'appId':'com.afda', 'MessageBody'： [ {place:'index'} ] }";
		
		//模拟手机
//		1.随机生成密码secret
		String uuid = "12345678"; //
//		2.AES加密并Base64编码
		byte[] aesEncryptData = getDataByAesEncrypt(jsondata,uuid.getBytes());
		System.out.println("uuid==================:"+RSAUtil.bytesToString(aesEncryptData));
		//String data = new String(aesEncryptData);
//		3.计算加密后数据MD5值
		String m = HashUtil.md5(aesEncryptData); //m
//		4.RSA加密密码
		String k = HexUtil.encodeHexStr(RSAUtil.encrypt(uuid.getBytes())); //k
//		5.计算签名
		long timestamp = System.currentTimeMillis();
		String t = String.valueOf(timestamp); //t
		String paraStr = RSAUtil.appId + RSAUtil.token + m + t;
		String s = HashUtil.sha1(paraStr.getBytes()); //s
		String a = "com.ydsjws.mobileguard";
		System.out.println("yyw=======================");
		System.out.println(aesEncryptData);
		System.out.println("yyw=======================");
		//System.out.printf("m:%s%n k:%s%n t:%s%n s:%s%n a:%s%n data:%s%n",m,k,t,s,a,data);
		
		//服务端处理=====================================================
//		AppSecure obj = new AppSecure(request);
//		String receiveInfo = AppSecureUtil.getDecryptResult(obj);
		
		
		//TODO:step1  sha1 签名校验
		//TODO:step2  md5检验
		
		String password = new String(RSAUtil.decrypt(HexUtil.decodeHex(k.toCharArray())));
		System.out.println("password:" + password);
		
		String request = new String(AESUtil.decrypt(SharedBase64.decode(aesEncryptData), password));
		System.out.println("request:" + request);
		
		String response = "adsdsadsa";
		byte[] responseData = getDataByAesEncrypt(response, password.getBytes()); //返回数据结果
		byte[] sign = RSAUtil.sign(responseData); //数据签名
		System.out.println("sign:" + HexUtil.encodeHexStr(sign));
		
	//	System.out.printf("s:%s\nm:%s\nk:%s\nt:%s\ns:%s\n",s,m,k,t,s);
		//==
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	//===
}
